#!/bin/bash
set -e

cd $(dirname $0)/..

fatal()
{
    echo "[ERROR] " "$@"
    exit 1
}

print_log()
{
    EXIT=$?
    if [ $EXIT -ne 0 ]; then
        echo '***RIO LOGS***'
        cat ./rio-controller-log
        echo '***END RIO LOGS***'
    fi
}


if [[ ${ARCH} == amd64 ]]; then
    echo Running tests

    if grep -rnw ./tests/integration/ -e "Focus"; then
      fatal "Integration tests must not be focused"
    fi

    BUILDTAGS="test,static"
    go test -cover -tags "$BUILDTAGS" ./...

    k3s server --no-deploy traefik >/dev/null 2>&1 &
    sleep 30

    export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
    export PATH=$(pwd)/bin:$PATH

    RUN_API_VALIDATOR=true RUN_API_VALIDATOR_PORT=:7443 RUN_API_VALIDATOR_HOST=127.0.0.1 rio-controller --mesh-mode linkerd &> ./rio-controller-log &
    rio install --check 2>&1

    kubectl get po -n rio-system

    trap print_log exit

    echo 'Running integration tests...'
    go test ./tests/integration/... --integration-tests
fi
